package cn.wit.testalgorithms;

import java.sql.Date;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 连续数组
 * 
 * @author 16604
 *
 */
public class DemoArrayMax {
	public static void main(String[] args) {
		int[] a = { 0, 0, 1, 0, 0, 0, 1, 1 };
		int[] b = { 0, 1 };
		int[] e = { 0, 0, 1, 0, 0, 0, 1, 1 };
		int[] c = { 1, 1, 1, 1, 1, 1, 1, 1 };
		int[] h = { 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0,
				0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0,
				1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1 };
		int[] d = { 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1,
				1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0,
				0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 };

		// System.out.println(findMaxLength(a));
		// System.out.println(findMaxLength(b));
		// System.out.println(findMaxLength(c));
		// System.out.println(findMaxLength(d));
		// System.out.println(findMaxLength(e));
		System.out.println(findMaxLength(a));
	}

	public static int findMaxLength(int[] nums) {

		if (nums.length == 0)
			return 0;

		Map<Integer, Integer> map = new HashMap<>();
		// 对map赋值
		for (int i = 0; i < nums.length; i++) {
			map.put(i, nums[i]);
		}
		int[] dp = new int[map.size()];
		if (map.get(0) == 1) {
			dp[0] = 1;

		} else {
			dp[0] = -1;
			
		}
		// 对map数组进行整改
		for (int i = 1; i < map.size(); i++) {
			if (map.get(i) == 1) {
				dp[i] = dp[i - 1] + 1;
				
				
			} else {
				dp[i] = dp[i - 1] - 1;
				
			}
		}
		int max = 0;
		
		// 找出最大长度,字串不是从头开始

		for (int i = 0; i < map.size(); i++) {
			for (int j = i; j < map.size(); j++) {
				if (dp[i] == dp[j]) {
					if (max < (j - i)) {
						max = (j - i);
					}
				}
			}
		}
		// 从头开始
		for (int i = 0; i < map.size(); i++) {
			if (dp[i] == 0 && i > max)
				max = i + 1;
		}
		
		return max;
	}

}
